package com.company.service;

import com.company.service.verifier.BaseHealthChecker;
import com.company.service.verifier.CacheHealthChecker;
import com.company.service.verifier.DatabaseHealthChecker;
import com.company.service.verifier.NetworkHealthChecker;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ApplicationStartupUtil {
	private static List<BaseHealthChecker> _services;
	private static CountDownLatch _latch;
	
	private ApplicationStartupUtil() {
	}

	private static class ApplicationHolder{
		public final static ApplicationStartupUtil INSTANCE = new ApplicationStartupUtil();
	}

	
	public static ApplicationStartupUtil getInstance() {
		return ApplicationHolder.INSTANCE;
	}

	/**
	 * @return 是否所有线程都运行正常(前题是所有的线程都执行完成)
	 * @throws Exception
	 */
	public  boolean checkExternalServices() throws Exception {
		_latch = new CountDownLatch(3);
		_services = new ArrayList<>();
		_services.add(new NetworkHealthChecker(_latch));
		_services.add(new CacheHealthChecker(_latch));
		_services.add(new DatabaseHealthChecker(_latch));

		ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(_services.size());
		
		for(final BaseHealthChecker v : _services) {
			executor.execute(v);
		}
		// 启动所有的线程后 主线程开始等待
		_latch.await();
		/*================此处已经执行完成======================*/
		for(final BaseHealthChecker v : _services) {
			if( ! v.isServiceUp()) {
				return false;
			}
		}
		executor.shutdown(); // 线程池需要关闭 不然核心线程会一直等待
		return true;
	}
	
	
}
